package com.xiebishe.mylibrary.net.okhttp;

import com.xiebishe.mylibrary.BuildConfig;
import com.xiebishe.mylibrary.base.MyApplication;

import java.io.File;
import java.security.SecureRandom;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpHelper {

    public static final OkHttpClient createOkHttpClient(int connectTimeout, int readTimeout, int writeTimeout, List<Interceptor> interceptors) {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        File httpCache = MyApplication.getInstance().getApplicationContext().getExternalFilesDir("httpCache");
        if (httpCache == null) {
            File cacheDir = MyApplication.getInstance().getApplicationContext().getCacheDir();
            httpCache = new File(cacheDir, "httpCache");
        }
        builder.cache(new Cache(httpCache, 100 * 1024 * 1024));
        builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        builder.readTimeout(readTimeout, TimeUnit.SECONDS);
        if (writeTimeout > 0) {
            builder.writeTimeout(writeTimeout, TimeUnit.SECONDS);
        }
        if (interceptors != null) {
            for (Interceptor interceptor : interceptors) {
                builder.addInterceptor(interceptor);
            }
        }
        if (BuildConfig.DEBUG){
            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
            logInterceptor.level(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logInterceptor);
        }
        if (MyApplication.Companion.getCanTrustAll()) {
            try {
                builder.sslSocketFactory(MyApplication.getInstance().createSSLSocketFactory());
                builder.hostnameVerifier((hostname, session) -> true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //如果是Debug模式，添加随时读取baseurl的Interceptor
        return builder.build();
    }



}
